﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using DeMeng.Common.Utilities;

namespace DeMeng.Common.Jwt
{
    public static class TokenHelper
    {
        public static string CreateJwtToken(string userId, int clientIdentityType, int userIdentity)
        {
            //var setting = ManagerConfig.GetManagerSection("JwtSettings");

            #region 设置用户角色
            var Role = string.Empty;
            switch (userIdentity)
            {
                case 1:
                    Role = string.Empty;
                    break;
                case 2:
                    Role = "Boss";
                    break;
                case 3:
                    if (clientIdentityType == 1)
                        Role = "Manager";
                    break;
                default:
                    break;
            } 
            #endregion

            //var jwtSettings = Newtonsoft.Json.JsonConvert.DeserializeObject<JwtSettings>(setting);
            var jwtSettings = ManagerConfig.GetManagerSection<JwtSettings>("JwtSettings");
            var signingKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,
                audience: jwtSettings.Audience,
                claims: new List<Claim> {
                    new Claim(JwtRegisteredClaimNames.Jti, userId),
                    new Claim("ClientIdentityType", clientIdentityType.ToString()),
                    new Claim(ClaimTypes.Role,Role)
                },
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
